package com.example.gateway.designPattern.observer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ClassName: WechatServer
 * @Description:
 * @Author: YourName
 * @Date: 2024/12/31
 */

public class WechatServer implements Subject{

    // 维护观察者列表  使用线程安全的 CopyOnWriteArrayList
    CopyOnWriteArrayList<Observer> list ;
    private String message;

    public WechatServer(){
        list = new CopyOnWriteArrayList<>();
    }


    @Override
    public void registerObserver(Observer observer) {
        list.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        if (!list.isEmpty()) {
            list.remove(observer);
        }
    }

    @Override
    public void notifyObserver() {
        for (Observer observer : list) {
            observer.update(message);
        }
    }


    /**
    *  发布消息
    */

    public void setInfomation(String s) {
        this.message = s;
        System.out.println("WeChat service update message： " + s);
        // 消息更新，通知所有观察者
        notifyObserver();
    }
}
